<template>
  <div class="fan-interaction-container">
    <!-- 头部 -->
    <div class="interaction-header">
      <el-button 
        icon="ArrowLeft" 
        circle 
        @click="goBack"
        class="back-btn"
      />
      <h2 class="header-title">粉丝互动</h2>
      <el-button 
        icon="Refresh" 
        circle 
        @click="refreshData"
      />
    </div>

    <!-- 标签页 -->
    <div class="tabs-section">
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="活动投票" name="activity-voting">
          <!-- 活动投票区域 -->
          <div class="voting-section">
            <!-- 当前活动信息 -->
            <div v-if="currentActivity" class="current-activity">
              <div class="activity-banner" v-if="currentActivity.bannerImage">
                <img :src="currentActivity.bannerImage" :alt="currentActivity.name" />
              </div>
              <div class="activity-info">
                <h3 class="activity-title">{{ currentActivity.name }}</h3>
                <p class="activity-description">{{ currentActivity.description }}</p>
                <div class="activity-time">
                  <span>开始时间: {{ formatDateTime(currentActivity.startTime) }}</span>
                  <span>结束时间: {{ formatDateTime(currentActivity.endTime) }}</span>
                </div>
                <div class="activity-rules" v-if="currentActivity.rules">
                  <h4>活动规则:</h4>
                  <p>{{ currentActivity.rules }}</p>
                </div>
              </div>
            </div>

            <!-- 活动艺人投票列表 -->
            <div v-if="votingArtists.length > 0" class="voting-list">
              <h3 class="section-title">参与艺人投票榜</h3>
              <div 
                v-for="(artist, index) in votingArtists" 
                :key="artist.artistId"
                class="voting-item"
              >
                <div class="rank-number">{{ artist.rank || index + 1 }}</div>
                <div class="artist-info">
                  <el-avatar 
                    :size="50"
                    :src="artist.artistAvatar"
                    :icon="artist.artistAvatar ? undefined : 'User'"
                  />
                  <div class="artist-details">
                    <h4>{{ artist.artistName }}</h4>
                    <p>{{ artist.voteCount }} 票 ({{ artist.uniqueVoters || 0 }} 人参与)</p>
                  </div>
                </div>
                <div class="vote-count">
                  {{ artist.voteCount }} 票
                </div>
                <el-button 
                  :type="artist.hasVoted ? 'info' : 'primary'"
                  :disabled="artist.hasVoted"
                  size="small"
                  @click="voteForArtistInActivity(artist)"
                >
                  {{ artist.hasVoted ? '已投' : '投票' }}
                </el-button>
              </div>
            </div>

            <!-- 无活动提示 -->
            <div v-else-if="!currentActivity" class="no-activity">
              <el-empty description="当前没有进行中的活动">
                <el-button type="primary" @click="refreshData">刷新</el-button>
              </el-empty>
            </div>

            <!-- 无艺人提示 -->
            <div v-else-if="votingArtists.length === 0" class="no-artists">
              <el-empty description="该活动暂无参与艺人">
                <el-button type="primary" @click="refreshData">刷新</el-button>
              </el-empty>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="艺人投票" name="artists">
          <!-- 艺人投票区域（兼容旧版本） -->
          <div class="voting-section">
            <h3 class="section-title">人气投票榜</h3>
            <div class="voting-list">
              <div 
                v-for="(artist, index) in legacyVotingArtists" 
                :key="artist.artistId"
                class="voting-item"
              >
                <div class="rank-number">{{ index + 1 }}</div>
                <div class="artist-info">
                  <el-avatar 
                    :size="50"
                    :src="artist.artistAvatar"
                    :icon="artist.artistAvatar ? undefined : 'User'"
                  />
                  <div class="artist-details">
                    <h4>{{ artist.artistName }}</h4>
                    <p>{{ artist.voteCount }} 票</p>
                  </div>
                </div>
                <div class="vote-count">
                  {{ artist.voteCount }} 票
                </div>
                <el-button 
                  :type="artist.hasVoted ? 'info' : 'primary'"
                  :disabled="artist.hasVoted"
                  size="small"
                  @click="voteForArtistLegacy(artist)"
                >
                  {{ artist.hasVoted ? '已投' : '投票' }}
                </el-button>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="冷知识" name="trivia">
          <!-- 冷知识区域 -->
          <div class="trivia-section">
            <h3 class="section-title">音乐冷知识</h3>
            <div v-if="triviaList.length > 0" class="trivia-content">
              <div class="trivia-card">
                <h4>{{ triviaList[currentTriviaIndex].title }}</h4>
                <p>{{ triviaList[currentTriviaIndex].content }}</p>
                <div class="trivia-navigation">
                  <el-button @click="previousTrivia" :disabled="triviaList.length <= 1">
                    上一个
                  </el-button>
                  <span class="trivia-counter">
                    {{ currentTriviaIndex + 1 }} / {{ triviaList.length }}
                  </span>
                  <el-button @click="nextTrivia" :disabled="triviaList.length <= 1">
                    下一个
                  </el-button>
                </div>
              </div>
            </div>
            <div v-else class="no-trivia">
              <el-empty description="暂无冷知识内容" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getCurrentActivity, 
  getActivityVoteLeaderboard,
  getVoteLeaderboard 
} from '@/api/activity'
import { voteForArtist } from '@/api/vote'
import type { Activity, VoteLeaderboard } from '@/types'
import { formatDateTime } from '@/utils/format'

const router = useRouter()

// 响应式数据
const activeTab = ref('activity-voting')
const currentActivity = ref<Activity | null>(null)
const votingArtists = ref<VoteLeaderboard[]>([])
const legacyVotingArtists = ref<VoteLeaderboard[]>([])
const triviaList = ref<any[]>([])
const currentTriviaIndex = ref(0)

// 返回上一页
const goBack = () => {
  router.back()
}

// 刷新数据
const refreshData = () => {
  if (activeTab.value === 'activity-voting') {
    fetchCurrentActivity()
  } else if (activeTab.value === 'artists') {
    fetchLegacyVotingData()
  } else {
    fetchTriviaData()
  }
  ElMessage.success('数据已刷新')
}

// 处理标签页切换
const handleTabChange = () => {
  if (activeTab.value === 'activity-voting') {
    fetchCurrentActivity()
  } else if (activeTab.value === 'artists') {
    fetchLegacyVotingData()
  } else {
    fetchTriviaData()
  }
}

// 为活动艺人投票
const voteForArtistInActivity = async (artist: VoteLeaderboard) => {
  if (!currentActivity.value) return
  
  try {
    await voteForArtist(artist.artistId, currentActivity.value.id)
    artist.hasVoted = true
    artist.voteCount += 1
    ElMessage.success('投票成功！')
  } catch (error: any) {
    console.error('投票失败:', error)
    ElMessage.error(error.message || '投票失败')
  }
}

// 为艺人投票（兼容旧版本）
const voteForArtistLegacy = async (artist: VoteLeaderboard) => {
  try {
    await voteForArtist(artist.artistId, 0) // 旧版本不需要活动ID
    artist.hasVoted = true
    artist.voteCount += 1
    ElMessage.success('投票成功！')
  } catch (error: any) {
    console.error('投票失败:', error)
    ElMessage.error(error.message || '投票失败')
  }
}

// 上一个冷知识
const previousTrivia = () => {
  if (triviaList.value.length > 0) {
    currentTriviaIndex.value = currentTriviaIndex.value > 0 
      ? currentTriviaIndex.value - 1 
      : triviaList.value.length - 1
  }
}

// 下一个冷知识
const nextTrivia = () => {
  if (triviaList.value.length > 0) {
    currentTriviaIndex.value = currentTriviaIndex.value < triviaList.value.length - 1 
      ? currentTriviaIndex.value + 1 
      : 0
  }
}

// 获取当前活动
const fetchCurrentActivity = async () => {
  try {
    const response = await getCurrentActivity()
    currentActivity.value = response.data
    
    if (currentActivity.value) {
      // 获取活动投票排行榜
      await fetchActivityVotingData()
    }
  } catch (error) {
    console.error('获取当前活动失败:', error)
    currentActivity.value = null
    votingArtists.value = []
  }
}

// 获取活动投票数据
const fetchActivityVotingData = async () => {
  if (!currentActivity.value) return
  
  try {
    const response = await getActivityVoteLeaderboard(currentActivity.value.id, { limit: 20 })
    votingArtists.value = response.data.leaderboard
  } catch (error) {
    console.error('获取活动投票数据失败:', error)
    ElMessage.error('获取活动投票数据失败')
  }
}

// 获取旧版本投票数据
const fetchLegacyVotingData = async () => {
  try {
    const response = await getVoteLeaderboard({ limit: 10 })
    legacyVotingArtists.value = response.data
  } catch (error) {
    console.error('获取投票数据失败:', error)
    ElMessage.error('获取投票数据失败')
  }
}

// 获取冷知识数据
const fetchTriviaData = async () => {
  try {
    // 这里应该调用冷知识API
    // const response = await triviaApi.getList()
    // triviaList.value = response.data
    triviaList.value = [
      {
        title: '音乐的力量',
        content: '研究表明，听音乐可以降低血压、减少焦虑，甚至能提高记忆力。'
      },
      {
        title: '古典音乐的起源',
        content: '古典音乐起源于欧洲，大约在1750-1820年间，以海顿、莫扎特、贝多芬为代表。'
      }
    ]
  } catch (error) {
    console.error('获取冷知识数据失败:', error)
    ElMessage.error('获取冷知识数据失败')
  }
}

// 初始化
onMounted(() => {
  fetchCurrentActivity()
  fetchTriviaData()
})
</script>

<style scoped>
.fan-interaction-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.interaction-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  gap: 20px;
}

.back-btn {
  margin-right: 10px;
}

.header-title {
  margin: 0;
  flex: 1;
  font-size: 24px;
  color: #333;
}

.tabs-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.voting-section,
.trivia-section {
  padding: 20px;
}

.current-activity {
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
}

.activity-banner img {
  width: 100%;
  max-height: 200px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 20px;
}

.activity-title {
  font-size: 24px;
  margin: 0 0 10px 0;
}

.activity-description {
  margin: 0 0 15px 0;
  opacity: 0.9;
}

.activity-time {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  font-size: 14px;
}

.activity-rules h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
}

.activity-rules p {
  margin: 0;
  opacity: 0.9;
  line-height: 1.6;
}

.section-title {
  font-size: 20px;
  margin: 0 0 20px 0;
  color: #333;
}

.voting-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.voting-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  gap: 15px;
}

.rank-number {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #ff6b6b, #ee5a24);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 16px;
}

.artist-info {
  display: flex;
  align-items: center;
  gap: 15px;
  flex: 1;
}

.artist-details h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #333;
}

.artist-details p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.vote-count {
  font-weight: bold;
  color: #ff6b6b;
  font-size: 16px;
  min-width: 80px;
  text-align: center;
}

.no-activity,
.no-artists {
  text-align: center;
  padding: 40px;
}

.trivia-content {
  max-width: 600px;
  margin: 0 auto;
}

.trivia-card {
  background: #f8f9fa;
  padding: 30px;
  border-radius: 12px;
  text-align: center;
}

.trivia-card h4 {
  font-size: 20px;
  margin: 0 0 20px 0;
  color: #333;
}

.trivia-card p {
  font-size: 16px;
  line-height: 1.8;
  color: #666;
  margin: 0 0 30px 0;
}

.trivia-navigation {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
}

.trivia-counter {
  font-size: 14px;
  color: #999;
  min-width: 60px;
}

.no-trivia {
  text-align: center;
  padding: 40px;
}

@media (max-width: 768px) {
  .fan-interaction-container {
    padding: 15px;
  }
  
  .interaction-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .activity-time {
    flex-direction: column;
    gap: 10px;
  }
  
  .voting-item {
    flex-direction: column;
    text-align: center;
    gap: 10px;
  }
  
  .artist-info {
    flex-direction: column;
    text-align: center;
  }
}
</style> 
</style> 